var grid;
var form;
var form1;
$(function () {

    //加载该页面前，先判断该模块的权限
    //获取当前登录的用户的权限
    var permission = document.cookie.split(";")[1].split("=")[1];
    var b = String(permission).split('');
    for (var i = 0; i < b.length; i++) {
        console.log(b[i]);
    }
    var moudle21 = b[4];
    //如果模块权限为1，即只能查询此模块下的数据，不能进行修改（禁用和重置密码不能使用）
    //系统管理
    flag = true;
    if (moudle21 == 1) {
        $("#productAddBtn").css('display', 'none');
        flag = false;
    }

    var pageNo = 1;
    var pageSize = 5;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";

    //初始化数据表格
    grid = $(grid_selector).jqGrid({
        datatype: "json",
        url: 'getProductList',
        mtype: 'POST',
        page: pageNo,
        postData: {
            'bankid': $("#productBank option:selected").val(),
            'loanName': $("#productName").val(),
            'seriesid': $("#productSerie option:selected").val(),
            'state': $("#productState option:selected").val(),
        },
        height: 380,
        width: 300,
        colNames: ['删除', '变更至新状态', '所属银行', '产品名称', '产品系列', '产品状态', '额度下线（元）', '额度上线（元）', '最长期限（月）', '利率下限（%）', '利率上限（%）',],
        colModel: [
            /*  {name:'id',index:'id', width:50, sortable:false, align:'center',hide:true},
              {name:'bookName',index:'bookName', sortable:false,align:'center'},
              {name:'isbn',index:'isbn',align:'center'},
              {name:'price',index:'price',align:'center'},
              {name:'stock',index:'stock',align:'center'},	*/

            //产品删除
            {
                name: 'id',
                index: 'delete',
                width: 100,
                align: 'center',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    if (flag == false) {
                        return "<button disabled class='btn btn-group btn-xs' onclick='deleteProduct(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>删除</button>";
                    } else {
                        return "<button class='btn btn-group btn-xs' onclick='deleteProduct(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>删除</button>";
                    }
                }
            },

            //产品状态更新
            {
                name: '',
                index: '',
                width: 120,
                align: 'center',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    if (flag == false) {
                        return "<select disabled onchange='productUpdateState(this.value," + rowObject.id + ")'><option value='0' style='display:none'>" + rowObject.productState + "</option><option value='1'>启用</option><option value='2'>暂停</option><option value='3'>终止</option></select>";
                    } else {
                        return "<select onchange='productUpdateState(this.value," + rowObject.id + ")'><option value='0' style='display:none'>" + rowObject.productState + "</option><option value='1'>启用</option><option value='2'>暂停</option><option value='3'>终止</option></select>";
                    }
                }
            },

            {name: 'bankname', index: 'bankname', sortable: false, align: 'center'},

            //产品名称
            {
                name: 'loanName',
                index: 'loanName',
                width: 120,
                align: 'center',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    if (rowObject.productState == "暂停") {
                        if (flag == false) {
                            return "<a href='javascript:void(0);' disabled='disabled' onclick='getProductinfo(\"" + rowObject.id + "\")'>" + cellvalue + "</a>";
                        } else {
                            return "<a href='javascript:void(0);' onclick='getProductinfo(\"" + rowObject.id + "\")'>" + cellvalue + "</a>";
                        }
                    } else {
                        if (flag == false) {
                            return "<a disabled='disabled' href='javascript:void(0);'>" + cellvalue + "</a>";
                        } else {
                            return "<a href='javascript:void(0);'>" + cellvalue + "</a>";
                        }
                    }
                }
            },


            {name: 'serieName', index: 'serieName', sortable: false, align: 'center'},
            {name: 'productState', index: 'productState', sortable: false, align: 'center'},
            {name: 'benefitsDown', index: 'benefitsDown', sortable: false, align: 'center'},
            {name: 'benefitsUp', index: 'benefitsUp', sortable: false, align: 'center'},
            {name: 'longestperiod', index: 'longestperiod', sortable: false, align: 'center'},
            {name: 'rateDown', index: 'rateDown', sortable: false, align: 'center'},
            {name: 'rateUp', index: 'rateUp', sortable: false, align: 'center'},

        ],
        viewrecords: true,
        rowNum: pageSize,
        rownumbers: false,//添加左侧行号
        rowList: [5, 10, 15],
        pager: pager_selector,
        altRows: true,
        multiselect: false,
        loadComplete: function (data) {
            var table = this;
            setTimeout(function () {
                updatePagerIcons(table);
            }, 0);
            var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);
        },
        autowidth: true,
        jsonReader: jsonReader,   // json中代表实际模型数据的入口
        rownumWidth: 55,
        prmNames: prmNames,
        recordtext: "显示 {0} - {1} 条 , 共 {2} 条",
        emptyrecords: "没有记录",
        loadtext: "加载中...",
        pgtext: "第 {0} 页  ,共 {1} 页"
    });

    //初始化分页条
    showNavGrid(grid_selector, pager_selector);

    //初始化信息校验表单
    form = $("#addform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });
    form1 = $("#Editform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });

    //加载所属银行、产品系列、产品状态
    var selectCompany = $("#productBank");//所属银行
    var selectOrg = $("#productSerie");//产品系列
    var selectRole = $("#productState");//产品状态
    $.ajax({
        url: "getproductindexSelect",
        type: "GET",
        dataType: "json",
        success: function (data) {
            if (data != null) {
                var company = data.allBankName;//所属银行
                var serie = data.allSerie;//产品系列
                var state = data.allState;//产品状态
                // console.log("company:"+company.length);
                // console.log("serie:"+serie.length);
                // console.log("state:"+state.length);
                selectCompany.html("");
                selectOrg.html("");
                selectRole.html("");
                //向所属银行select传入数据
                var options = "<option value=\"0\">---全部---</option>";
                for (var i = 0; i < company.length; i++) {
                    options += "<option value=\"" + company[i].id + "\">" + company[i].bankname + "</option>";
                }
                //向产品系列select传入数据
                var optionss = "<option value=\"0\">---全部---</option>";
                for (var i = 0; i < serie.length; i++) {
                    optionss += "<option value=\"" + serie[i].id + "\">" + serie[i].serieName + "</option>";
                }
                //向产品状态select传入数据
                var optionsss = "<option value=\"0\">---全部---</option>";
                for (var i = 0; i < state.length; i++) {
                    optionsss += "<option value=\"" + state[i].id + "\">" + state[i].productState + "</option>";
                }


                selectCompany.html(options);
                selectOrg.html(optionss);
                selectRole.html(optionsss);
            }
        }
    })


    //通过条件查询产品
    $("#queryBtn").click(function () {
        var filters = {
            'bankid': $("#productBank option:selected").val(),
            'loanName': $("#productName").val(),
            'seriesid': $("#productSerie option:selected").val(),
            'state': $("#productState option:selected").val()
        }
        grid.jqGrid("setGridParam", {postData: filters, page: 1});
        grid.trigger('reloadGrid');
    });

});


//清空查询条件
$("#clearBtn").click(function () {
    $("#productBank").val(0);
    $("#productName").val("");
    $("#productSerie").val(0);
    $("#productState").val(0);
});


//产品删除
function deleteProduct(obj) {
    if (confirm("确定要删除该产品？")) {
        $.ajax({
            url: "deleteProduct?productId=" + obj,
            type: "post",
            success: function (data) {

                if (data.deleteResult == 1) {
                    alert("产品删除成功");
                    grid.trigger('reloadGrid');
                    // loadPage('incremental/product_index.html');
                } else {
                    alert("产品删除失败");
                }
            },
            error: function (data) {
                alert("产品删除失败");
            }
        })
    }
}


//更新产品状态
function productUpdateState(obj1, obj2) {
    // alert("产品状态："+obj1);
    // alert("产品ID："+obj2);
    if (confirm("确定要更改该产品的状态吗？")) {
        $.ajax({
            url: "updateProductState?id=" + obj2 + "&state=" + obj1,
            type: "post",
            success: function (data) {
                if (data.updateResult == 1) {
                    alert("状态修改成功");
                    grid.trigger('reloadGrid');
                    // loadPage('incremental/product_index.html');
                } else {
                    alert("状态修改失败");
                }
            },
            error: function (data) {
                alert("状态修改失败");
            }
        })
    }
}

//设置cookie
var setCookie = function (name, value, day) {
    //当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
    var expires = day * 24 * 60 * 60 * 1000;
    var exp = new Date();
    exp.setTime(exp.getTime() + expires);
    document.cookie = name + "=" + value + ";expires=" + exp.toUTCString();
};
//删除cookie
var delCookie = function (name) {
    setCookie(name, ' ', -1);
};


//获取产品详细信息
function getProductinfo(obj) {
    // alert("修改产品的id："+obj);
    //传递cookie
    setCookie('id', obj, 7)
    loadPage("incremental/update_product.html");
    // delCookie('id',' ',-1)


}


